document.addEventListener('DOMContentLoaded', function() {
    const baseURL = 'http://127.0.0.1:5000'; // 本地代理的Flask服务器
    const searchButton = document.getElementById('searchButton');
    const searchInput = document.getElementById('searchInput');
    const songResults = document.getElementById('songResults');
    const albumResults = document.getElementById('albumResults');
    const mvResults = document.getElementById('mvResults');
    const songResultList = songResults ? songResults.querySelector('.result-list') : null;
    const albumResultList = albumResults ? albumResults.querySelector('.result-list') : null;
    const mvResultList = mvResults ? mvResults.querySelector('.result-list') : null;
    const loadingIndicator = document.getElementById('loadingIndicator');

    let currentPage = 1;
    let isLoading = false;
    let currentTab = 'songResults';
    let currentKeyword = '';

    const musicPlayer = document.getElementById('music-player');
    const albumCover = document.getElementById('album-cover');
    const songNameElement = document.getElementById('song-name');
    const singerNameElement = document.getElementById('singer-name');
    const playButton = document.getElementById('play-button');
    const prevButton = document.getElementById('prev-button');
    const nextButton = document.getElementById('next-button');
    const progressBar = document.getElementById('progress-bar');
    const currentTimeElement = document.getElementById('current-time');
    const totalTimeElement = document.getElementById('total-time');
    const currentLyricElement = document.getElementById('current-lyric');
    const lyricsButton = document.getElementById('lyrics-button');
    const playModeButton = document.getElementById('play-mode');
    const lyricsModal = document.getElementById('lyrics-modal');
    const closeLyricsBtn = document.getElementById('close-lyrics');
    const lyricsContent = document.getElementById('lyrics-content');
    const volumeSlider = document.getElementById('volume-slider');

    let playlist = [];
    let currentSongIndex = 0;
    let audio = null;
    let isSeeking = false;
    let playMode = 'sequence'; // 'sequence', 'shuffle', 'repeat'
    let parsedLyrics = [];

    function search(keyword, type, page, callback) {
        isLoading = true;
        fetch(`${baseURL}/search?key=${keyword}&t=${type}&pageNo=${page}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error(data.error);
                    isLoading = false;
                    return;
                }
                callback(data.data.list);
                isLoading = false;
            })
            .catch(error => {
                console.error('Error fetching search results:', error);
                isLoading = false;
            });
    }

    function displaySongs(songs) {
    songs.forEach((song, index) => {
        const songItem = document.createElement('li');
        songItem.classList.add('result-item');
        const singerLinks = song.singer.map(s => `<a href="/singer_detail?singer_id=${s.mid}" class="singer-link">${s.name}</a>`).join(', ');
        songItem.innerHTML = `
            <div>${song.songname}</div>
            <div>${singerLinks}</div>
            <div>${song.albumname}</div>
            <div>${formatTime(song.interval)}</div>
        `;
        songItem.addEventListener('click', function() {
            currentSongIndex = index;
            playCurrentSong(song);
        });
        songResultList.appendChild(songItem);
    });

    document.querySelectorAll('.singer-link').forEach(link => {
        link.addEventListener('click', function(event) {
            event.stopPropagation(); // 防止事件冒泡到父级的点击事件
        });
    });
}


    function displayAlbums(albums) {
        albums.forEach(album => {
            const albumItem = document.createElement('li');
            albumItem.classList.add('result-item');
            albumItem.innerHTML = `
                <div>${album.albumname}</div>
                <div>${album.singername}</div>
                <div>${formatDate(album.pubtime)}</div>
            `;
            albumResultList.appendChild(albumItem);
        });
    }

    function displayMvs(mvs) {
        mvs.forEach(mv => {
            const mvItem = document.createElement('div');
            mvItem.classList.add('result-item');
            mvItem.innerHTML = `
                <img src="${mv.picurl}" alt="MV Cover">
                <div>${mv.videoname}</div>
                <div>${mv.singername}</div>
            `;
            mvResultList.appendChild(mvItem);
        });
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    }

    function formatDate(timestamp) {
        const date = new Date(timestamp * 1000);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    }

    function playCurrentSong(song) {
        const songMid = song.songmid;
        const songName = song.songname;
        const singerName = song.singer.map(s => s.name).join(', ');
        const albumCover = `http://y.gtimg.cn/music/photo_new/T002R300x300M000${song.albummid}.jpg`;

        fetch(`${baseURL}/user/refresh`, { method: 'GET', credentials: 'include' })
            .then(() => fetchPlayUrl(songMid))
            .then(songUrl => {
                if (songUrl) {
                    updatePlayer(songUrl, songName, singerName, albumCover);
                    playSong(songUrl);
                    fetchLyrics(songMid)
                        .then(lyrics => {
                            parsedLyrics = parseLyrics(lyrics);
                        })
                        .catch(error => console.error('Error fetching lyrics:', error));
                } else {
                    console.error('无法获取播放链接');
                }
            })
            .catch(error => console.error('Error:', error));
    }

    function fetchPlayUrl(songMid) {
        return fetch(`${baseURL}/song/url?id=${songMid}`, {
            method: 'GET',
            credentials: 'include'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.result !== 100) {
                throw new Error('API response error: ' + data.result);
            }
            return data.data;  // 假设播放链接在 data.data 中
        })
        .catch(error => {
            console.error('Error fetching play URL:', error);
            return null; // 返回 null 表示无法获取播放链接
        });
    }

    function playSong(url) {
        if (audio) {
            audio.pause();
        }
        audio = new Audio(url);
        audio.play()
            .then(() => {
                musicPlayer.style.display = 'flex';
                setTimeout(() => {
                    musicPlayer.style.opacity = 1;
                }, 10);
                playButton.textContent = '⏸️';
                updateProgressBar();
                updateCurrentLyric();

                audio.addEventListener('ended', function() {
                    if (playMode === 'repeat') {
                        playCurrentSong();
                    } else {
                        nextButton.click();
                    }
                });
            })
            .catch(error => console.error('Error playing song:', error));
    }

    function updatePlayer(url, songName, singerName, albumCoverUrl) {
        albumCover.src = albumCoverUrl;
        songNameElement.textContent = songName;
        singerNameElement.textContent = singerName;
        musicPlayer.style.display = 'flex';
        setTimeout(() => {
            musicPlayer.style.opacity = 1;
        }, 10);
    }

    function fetchLyrics(songMid) {
        return fetch(`${baseURL}/lyric?songmid=${songMid}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                return data.data.lyric;
            });
    }

    function showLyrics(lyrics) {
        lyricsContent.innerHTML = lyrics.replace(/\n/g, '<br>');
        lyricsModal.style.display = 'block';
    }

    function updateCurrentLyric() {
        if (!parsedLyrics || parsedLyrics.length === 0) return;

        let currentLyric = '';
        const currentTime = Math.floor(audio.currentTime);

        for (let i = 0; i < parsedLyrics.length; i++) {
            if (currentTime >= parsedLyrics[i].time) {
                currentLyric = parsedLyrics[i].text;
            } else {
                break;
            }
        }

        if (currentLyric !== currentLyricElement.textContent) {
            currentLyricElement.style.opacity = 0;
            setTimeout(() => {
                currentLyricElement.textContent = currentLyric;
                currentLyricElement.style.opacity = 1;
            }, 500); // 渐变时间
        }
    }

    function updateProgressBar() {
        if (audio && !isSeeking) {
            progressBar.max = Math.floor(audio.duration); // 取整
            progressBar.value = Math.floor(audio.currentTime); // 取整
            currentTimeElement.textContent = formatTime(Math.floor(audio.currentTime));
            totalTimeElement.textContent = formatTime(Math.floor(audio.duration));

            // 更新当前歌词
            updateCurrentLyric();
        }
        requestAnimationFrame(updateProgressBar);
    }

    progressBar.addEventListener('input', function() {
        isSeeking = true;
        currentTimeElement.textContent = formatTime(Math.floor(progressBar.value));
    });

    progressBar.addEventListener('change', function() {
        isSeeking = false;
        if (audio) {
            audio.currentTime = Math.floor(progressBar.value); // 取整
        }
    });

    playButton.addEventListener('click', function() {
        if (audio) {
            if (audio.paused) {
                audio.play();
                playButton.textContent = '⏸️';
                musicPlayer.style.opacity = 1;
            } else {
                audio.pause();
                playButton.textContent = '▶️';
                musicPlayer.style.opacity = 1; // 保持播放器显示
            }
        }
    });

    prevButton.addEventListener('click', function() {
        if (playMode === 'shuffle') {
            currentSongIndex = Math.floor(Math.random() * playlist.length);
        } else {
            currentSongIndex = (currentSongIndex - 1 + playlist.length) % playlist.length;
        }
        playCurrentSong(playlist[currentSongIndex]);
    });

    nextButton.addEventListener('click', function() {
        if (playMode === 'shuffle') {
            currentSongIndex = Math.floor(Math.random() * playlist.length);
        } else if (playMode === 'repeat') {
            // No need to change currentSongIndex, just replay the current song
        } else {
            currentSongIndex = (currentSongIndex + 1) % playlist.length;
        }
        playCurrentSong(playlist[currentSongIndex]);
    });

    lyricsButton.addEventListener('click', function() {
        if (parsedLyrics.length > 0) {
            showLyrics(parsedLyrics.map(lyric => lyric.text).join('\n'));
        }
    });

    closeLyricsBtn.addEventListener('click', function() {
        lyricsModal.style.display = 'none';
    });

    playModeButton.addEventListener('click', function() {
        if (playMode === 'sequence') {
            playMode = 'shuffle';
            playModeButton.textContent = '🔀';
        } else if (playMode === 'shuffle') {
            playMode = 'repeat';
            playModeButton.textContent = '🔂';
        } else {
            playMode = 'sequence';
            playModeButton.textContent = '🔁';
        }
    });

    volumeSlider.addEventListener('input', function() {
        if (audio) {
            audio.volume = volumeSlider.value;
        }
    });

    window.addEventListener('click', function(event) {
        if (event.target === lyricsModal) {
            lyricsModal.style.display = 'none';
        }
    });

    function parseLyrics(lyrics) {
        const lines = lyrics.split('\n');
        const parsedLyrics = [];
        lines.forEach(line => {
            const match = line.match(/\[(\d+):(\d+\.\d+)\](.*)/);
            if (match) {
                const time = parseInt(match[1]) * 60 + parseFloat(match[2]);
                const text = match[3];
                parsedLyrics.push({ time, text });
            }
        });
        return parsedLyrics;
    }

    searchButton.addEventListener('click', function() {
    const keyword = searchInput.value.trim();
    if (keyword) {
        window.location.href = `/result?key=${encodeURIComponent(keyword)}`;
    }
});


    searchInput.addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            searchButton.click();
        }
    });

    document.querySelectorAll('.result-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.result-tab').forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            document.querySelectorAll('.result-section').forEach(section => section.classList.remove('active'));
            document.getElementById(this.dataset.target).classList.add('active');
            currentTab = this.dataset.target;
        });
    });

    window.addEventListener('scroll', function() {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 2) {
            if (!isLoading) {
                currentPage++;
                if (currentTab === 'songResults') {
                    search(currentKeyword, 0, currentPage, displaySongs);
                } else if (currentTab === 'albumResults') {
                    search(currentKeyword, 8, currentPage, displayAlbums);
                } else if (currentTab === 'mvResults') {
                    search(currentKeyword, 12, currentPage, displayMvs);
                }
            }
        }
    });

    // 在 result.templates 页面加载时，执行搜索并显示结果
    const urlParams = new URLSearchParams(window.location.search);
    const searchKey = urlParams.get('key');
    if (searchKey && songResults && albumResults && mvResults) {
        currentKeyword = searchKey;
        search(searchKey, 0, currentPage, displaySongs);
        search(searchKey, 8, currentPage, displayAlbums);
        search(searchKey, 12, currentPage, displayMvs);
    }
});
